const request = require('../../utils/request.js');
const imageUrl = getApp().globalData.imageUrl
Page({
  data: {
    message:'',
    reddot:false,
    sortType: '综合排序',
    sortOptions: ['距离最近', '发布最新', '赏金由高到低', '赏金由低到高'],
    typeOptions: ['全选', '举手之劳', '出点小力', '重体力活', '失物搜寻', '跑腿帮忙', '公益活动', '急！重金求助'],
    noticeNeeds: 2,
    noticeMission: 1,
    selectedSortIndex: 0,
    selectedTypeIndex: 0,
    orders: [],
    showNotice: false,
    showSortOptions: false,
    showTypeOptions: false,
    showOtherFilters: false,
    OtherFiltersReverseAnime: false,
    selectedTime: '',
    rewardRange: 10000,
    distanceRange: 0,
    minPrice: '',
    maxPrice: '',
    typeSelected: {
      '全选': true,
      '举手之劳': true,
      '出点小力': true,
      '重体力活': true,
      '失物搜寻': true,
      '跑腿帮忙': true,
      '公益活动': true,
      '急！重金求助': true,
    },
    typeList: [
      '全选',
      '举手之劳',
      '出点小力',
      '重体力活',
      '失物搜寻',
      '跑腿帮忙',
      '公益活动',
      '急！重金求助',
    ],
    releaseTime: ''
  },

  onShow: function () {
    this.checkNewMessageInterval = setInterval(() => {
      const app = getApp();
      if (app.globalData.hasNewMessage) {
        // 设置页面数据
        this.setData({
          reddot: true,
        });
      }
    }, 1000); // 每秒检查一次
    this.setData({
      showNotice: false,
      showSortOptions: false,
      showTypeOptions: false,
      showOtherFilters: false
    })
    this.fetchOrders();
  },
  onHide() {
    // 清除定时器，避免内存泄漏
    clearInterval(this.checkNewMessageInterval);
  },
  fetchOrders: function (minPrice, maxPrice, distanceRange, releaseTime) {
    const that = this;
    // 调用微信的获取位置接口
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        const longitude = res.longitude;
        const latitude = res.latitude;
        const selectedTypes = Object.keys(that.data.typeSelected).filter(key => {
          return that.data.typeSelected[key] && key !== '全选'; // 使用 that 而不是 this
        });

        // 动态构建请求数据对象，只添加有值的字段
        const requestData = {
          "longitude": longitude, // 动态获取经度
          "latitude": latitude, // 动态获取纬度
          "sortType": that.data.sortType,
          "selection": selectedTypes,
          "pn": 1 // 页码
        };

        // 如果字段有值，才添加到请求数据中
        if (minPrice !== undefined && minPrice !== '') {
          requestData["Mininums"] = minPrice;
        }
        if (maxPrice !== undefined && maxPrice !== '') {
          requestData["Maxinums"] = maxPrice;
        }
        if (distanceRange !== undefined && distanceRange !== '' && distanceRange !== 0) {
          requestData["Range"] = distanceRange;
        }
        if (releaseTime !== undefined && releaseTime !== '') {
          requestData["released"] = releaseTime;
        }
        console.log(requestData)
        // 使用获取到的经纬度进行数据请求
        request.request("/home", "POST", requestData).then(response => {
          if (response.code === "200") {
            // 处理返回的数据
            const ordersData = response.data.list.map(order => ({
              id: order.id,
              title: order.title,
              category: order.type, // 假设有一个方法可以返回类型名称
              categoryColor: that.getCategoryColor(order.type),
              fontColor: that.getFontColor(order.type),
              author_img: `${imageUrl}${order.head}`, // 使用返回的头像路径
              author_nickname: order.name,
              location: order.location,
              reward: order.bountyAmount, // 悬赏金额
              time: that.getTime(order.distanceTime), // 转换为相对时间
              distance: that.formatDistance(order.distance) // 根据距离自动转换单位
            }));
            console.log(ordersData);
            that.setData({
              orders: ordersData
            });
          } else {
            console.error('请求失败，错误信息:', response.message);
            wx.showToast({
              title: '请求失败，请稍后重试',
              icon: 'none'
            });
          }
        }).catch(error => {
          console.error("获取订单数据失败：", error);
          wx.showToast({
            title: '获取订单数据失败',
            icon: 'none'
          });
        });
      },
      fail(err) {
        console.error('获取地理位置失败', err);
        wx.showToast({
          title: '无法获取当前位置',
          icon: 'none'
        });
      }
    });
  },

  // 用于根据距离自动选择合适的单位
  formatDistance: function (distance) {
    if (distance < 1000) {
      return `${distance.toFixed(2)}米`; // 距离小于1公里时显示为米
    } else {
      return `${(distance / 1000).toFixed(2)}公里`; // 距离大于等于1公里时显示为公里
    }
  },
  // 用于计算相对时间的方法
  getTime: function (distanceTime) {

    if (distanceTime < 60) {
      return '刚刚';
    } else if (distanceTime < 3600) {
      const minutes = Math.floor(distanceTime / 60);
      return `${minutes}分钟前`;
    } else if (distanceTime < 86400) {
      const hours = Math.floor(distanceTime / 3600);
      return `${hours}小时前`;
    } else {
      const days = Math.floor(distanceTime / 86400);
      return `${days}天前`;
    }
  },

  // 格式化时间（将时间戳转换为可读格式）
  formatTime: function (timestamp) {
    const date = new Date(timestamp);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  },
  getCategoryColor(type) {
    switch (type) {
      case '重体力活':
        return '#E48F1F'; // 橘色
      case '举手之劳':
        return '#86D903'; // 绿色
      case '急！重金求助':
        return '#C30018'; // 红色
      case '出点小力':
        return '#86D903';
      default:
        return '#99c8df'; // 默认灰色，如果类型不匹配时
    }
  },
  getFontColor(type) {
    switch (type) {
      case '重体力活':
        return '#7B4D12'; // 橘色
      case '举手之劳':
        return '#4B7902'; // 绿色
      case '急！重金求助':
        return '#FFFF00'; // 红色
      case '出点小力':
        return '#4B7902';
      default:
        return 'blue'; // 默认灰色，如果类型不匹配时
    }
  },
  navigateToSearch: function () {
    wx.navigateTo({
      url: '/subpackages/offlineAid-module/pages/search/search'
    });
  },

  navigateToAddOrder: function () {
    wx.navigateTo({
      url: '/subpackages/offlineAid-module/pages/write-post/write-post'
    });
  },

  openNotice: function () {
    this.setData({
      showNotice: !this.data.showNotice,
      showSortOptions: false,
      showTypeOptions: false,
      showOtherFilters: false,
      noticeNeeds: 2,
      noticeMission: 1,
    });



  },

  toggleSortOptions: function () {
    this.setData({
      showSortOptions: !this.data.showSortOptions,
      showTypeOptions: false,
      showOtherFilters: false,
      showNotice: false
    });
  },

  toggleTypeOptions: function () {
    this.setData({
      showTypeOptions: !this.data.showTypeOptions,
      showSortOptions: false,
      showOtherFilters: false,
      showNotice: false
    });
  },

  toggleOtherFilters: function () {
    this.setData({
      showOtherFilters: !this.data.showOtherFilters,
      showSortOptions: false,
      showTypeOptions: false,
      showNotice: false,
    });
  },

  closePopup: function () {
    this.setData({
      showSortOptions: false,
      showTypeOptions: false,
      showOtherFilters: false
    });
  },

  preventClose: function (e) {
    if (e && e.stopPropagation) {
      e.stopPropagation();
    }
  },

  closePopupAndApply: function () {
    this.setData({
      showSortOptions: false,
      showTypeOptions: false,
      showOtherFilters: false
    });
    // 这里可以添加应用逻辑
  },
  shuffleOption(options){
    let nums = [];
    let sortOption = options.map(option => {
      switch(option){
        case '综合排序':
          
          break;
        case '距离最近':
          break;
        case '发布最新':
          break;
        case '赏金由高到低':
          break;
        case '赏金由低到高':
          break;
        default:
          break;
      }
      return sortOption;
    });
  },

  setSortOption: function (e) {
    const sortType = e.currentTarget.dataset.value;
    let currentSortOption = this.data.sortOptions;
    let currentSortType = this.data.sortType;


    let updatedSortOption = currentSortOption.map(option => {
      return option === sortType ? currentSortType : option;
    });
    console.log(updatedSortOption)
    this.setData({
      sortType: sortType,
      sortOptions: updatedSortOption,
      showSortOptions: false
    })
    this.fetchOrders()
    // 这里可以添加排序逻辑
  },

  onTypeChange: function (e) {
    const selectedValue = e.currentTarget.dataset.value; // 获取当前点击的值
    let typeSelected = {
      ...this.data.typeSelected
    }; // 克隆当前的 typeSelected

    // 判断是否点击了"全选"
    if (selectedValue === '全选') {
      const allSelected = !typeSelected['全选']; // 取反全选状态
      // 将所有选项设置为与“全选”一致的状态
      for (let key in typeSelected) {
        typeSelected[key] = allSelected;
      }
    } else {
      // 取反当前选中的值
      typeSelected[selectedValue] = !typeSelected[selectedValue];

      // 检查除了"全选"以外的所有选项是否都被选中
      const allOptions = Object.keys(typeSelected).filter(key => key !== '全选');
      const allSelected = allOptions.every(key => typeSelected[key]);

      // 如果所有选项都被选中，则自动选中“全选”
      typeSelected['全选'] = allSelected;
    }

    // 更新数据并触发界面刷新
    this.setData({
      typeSelected: typeSelected
    });

    // 调用获取订单数据的逻辑
    this.fetchOrders();
  },







  applyOtherFilters: function () {
    const {
      minPrice,
      maxPrice,
      distanceRange,
      selectedTime
    } = this.data;
    let releaseTime = '';
    console.log(distanceRange)
    if (minPrice > maxPrice || minPrice < 0 || maxPrice < 0 || distanceRange < 0) {
      wx.showToast({
        title: '请输入合理的筛选条件',
        icon: 'none'
      });
      return;
    }

    switch (selectedTime) {
      case '5分钟内':
        releaseTime = 5 * 60
        break
      case '10分钟内':
        releaseTime = 10 * 60
        break
      case '30分钟内':
        releaseTime = 30 * 60
        break
      case '1小时内':
        releaseTime = 60 * 60
        break
      default:
        break
    }
    this.setData({
      showOtherFilters: false
    });

    this.fetchOrders(minPrice, maxPrice, distanceRange, releaseTime);
  },
  resetFilters: function () {
    this.setData({
      selectedTime: '',
      rewardRange: 10000,
      distanceRange: 0,
      minPrice: '',
      maxPrice: '',
    })
  },
  onRewardChange: function (e) {
    this.setData({
      rewardRange: e.detail.value
    });
  },

  onDistanceChange: function (e) {
    this.setData({
      distanceRange: e.detail.value
    });
  },
  navigateToMyorder: function (e) {
    const app = getApp();
    app.globalData.hasNewMessage = false;
    wx.navigateTo({
      url: `/subpackages/mine-module/pages/my_order/my_order`
    });
  },
  navigateToDetail: function (e) {
    const id = e.currentTarget.dataset.id;
    const distance = e.currentTarget.dataset.distance
    wx.navigateTo({
      url: `/subpackages/offlineAid-module/pages/post-detail/post-detail?helpId=${id}&role=1&distance=${distance}`
    });
  },
  onTimeChange: function (e) {
    const value = e.currentTarget.dataset.value;
    if (value === this.data.selectedTime) {
      this.setData({
        selectedTime: ''
      });
    } else {
      this.setData({
        selectedTime: value
      });
    }

  },
  onMinPriceInput: function (e) {
    this.setData({
      minPrice: e.detail.value
    });

  },
  onMaxPriceInput: function (e) {
    this.setData({
      maxPrice: e.detail.value
    });
  },
  jumpToMyNeed: function (e) {
    const app = getApp();
    app.globalData.hasNewMessage = false;
    wx.navigateTo({
      url: `/subpackages/mine-module/pages/my_order/my_order`
    })
  },
  jumpToMyMission: function (e) {
    const app = getApp();
    app.globalData.hasNewMessage = false;
    const index = 1
    wx.navigateTo({
      url: `/subpackages/mine-module/pages/my_order/my_order?index=${index}`
    })
  },

});